/*
 * Copyright (c) 2024. hallele, Inc All rights reserved.
 */

package cn.hallele.ms.portalcenter.application.action.auth.login.flow;

import cn.dev33.satoken.stp.StpUtil;
import cn.hallele.infrastructure.util.NetUtil;
import cn.hallele.infrastructure.util.ObjectUtil;
import cn.hallele.infrastructure.util.bean.LoginUser;
import cn.hallele.ms.portalcenter.application.action.auth.login.LoginApplicationService;
import cn.hallele.ms.portalcenter.application.bo.MenuBO;
import cn.hallele.ms.portalcenter.application.bo.RoleBO;
import cn.hallele.ms.portalcenter.application.bo.UserBO;
import cn.hallele.ms.starter.web.framework.node.ServiceFlow;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import lombok.extern.slf4j.Slf4j;

import java.util.stream.Collectors;

/**
 * 执行登录操作
 *
 * @author anle5
 * @since 2024/12/31 22:55
 */
@Slf4j
@LiteflowComponent
public class LoginFlow extends ServiceFlow {
    @Override
    public void process() throws Exception {
        UserBO userBO = this.getActionContext().getParams(LoginApplicationService.LOGIN_USER);
        StpUtil.login(userBO.getId());
        StpUtil.getTokenSession()
                .set(NetUtil.LOGIN_USER, LoginUser.builder()
                        .tenantId(userBO.getTenantId())
                        .id(userBO.getId())
                        .username(userBO.getUsername())
                        .avatar(userBO.getAvatar())
                        .phoneNumber(userBO.getPhoneNumber())
                        .email(userBO.getEmail())
                        .sex(userBO.getSex().getCode())
                        .age(userBO.getAge())
                        .status(userBO.getStatus().getCode())
                        .personalitySignature(userBO.getPersonalitySignature())
                        .passExpiredTime(userBO.getPassExpiredTime())
                        .accountExpiredTime(userBO.getAccountExpiredTime())
                        .accountExpiredTime(userBO.getAccountExpiredTime())
                        .createTime(userBO.getCreateTime())
                        .updateTime(userBO.getUpdateTime())
                        .createBy(userBO.getCreateBy())
                        .updateBy(userBO.getUpdateBy())
                        .roles(ObjectUtil.map(userBO.getRoles(), r -> r.stream().map(RoleBO::getCode).collect(Collectors.toSet())))
                        .perms(ObjectUtil.map(userBO.getMenus(), m -> m.stream().map(MenuBO::getPerm).collect(Collectors.toSet())))
                        .build());
    }
}
